import axios from 'axios'
import { Message } from 'element-ui'
import { Notification } from 'element-ui'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 1200000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data

    if (res instanceof Blob) {
      return res
    }

    if (res.code !== 0) {
      Message({
        message: res.message || '服务器忙，请稍后再试',
        type: 'error',
        duration: 5 * 1000
      })

      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res.data
    }
  },
  error => {
    Notification.error({
      title: '服务器忙，请稍后再试',
      duration: 5000
    })
    return Promise.reject(error)
  }
)

export default service
